import io.netty.buffer.ByteBuf
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}

/**
  * Created by IntelliJ IDEA.
  * Programmer : John Zn
  * Date : 2016/4/14 0014
  * Time : 22:11
  * Discribtion : 
  */
class ClientHandler extends ChannelInboundHandlerAdapter {
  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
    println("server exceptionCaught")
    ctx.close()
  }

  override def channelActive(ctx: ChannelHandlerContext): Unit = {
    println("client active and to wriite hello world")
//    ctx.writeAndFlush(NettyMsg(" hello world "))
        ctx.writeAndFlush(" hello world ")
  }

  override def channelRead(ctx: ChannelHandlerContext, msg: scala.Any): Unit = {
    //    println("client channelRead")
    //    println(msg)
    //    val byteBuf = msg.asInstanceOf[ByteBuf]
    //    val bytes = new Array[Byte](byteBuf.readableBytes())
    //    byteBuf.readBytes(bytes)
    //    val message = new String(bytes, "UTF-8")
    //    println(message)
    msg match {
      case message: String => println(s"string: $message")
      case NettyMsg(message) => println(s"string: $message")
    }
  }

  override def channelRegistered(ctx: ChannelHandlerContext): Unit = {
    println("client registered")
  }

  override def channelReadComplete(ctx: ChannelHandlerContext): Unit = {
    println("client read complete")
  }
}

